<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 6.0.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/ficon.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/icon.png">
  <link rel="mask-icon" href="/images/icon.png" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-minimal.min.css">
  <script src="/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"bqlin.github.io","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":true,"comments":{"style":"tabs","active":"gitalk","storage":true,"lazyload":false,"nav":{"gitalk":{"order":-2}},"activeClass":"gitalk"},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":-1,"unescape":false,"preload":false},"motion":{"enable":false,"async":true,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="与C语言交互发生在使用一些C语言编写的API上。C语言的语法会桥接到Swift中对应的语法中。Swift能很好地与C语言交互。 类型">
<meta property="og:type" content="article">
<meta property="og:title" content="Swift 与C语言交互">
<meta property="og:url" content="https://bqlin.github.io/posts/swift_interacts_with_c_language/index.html">
<meta property="og:site_name" content="權咚领域">
<meta property="og:description" content="与C语言交互发生在使用一些C语言编写的API上。C语言的语法会桥接到Swift中对应的语法中。Swift能很好地与C语言交互。 类型">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-08-19T11:16:47.000Z">
<meta property="article:modified_time" content="2021-08-19T11:16:47.000Z">
<meta property="article:author" content="權咚">
<meta property="article:tag" content="Apple">
<meta property="article:tag" content="Swift">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://bqlin.github.io/posts/swift_interacts_with_c_language/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Swift 与C语言交互 | 權咚领域</title>
  
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-105338942-1"></script>
    <script>
      if (CONFIG.hostname === location.hostname) {
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', 'UA-105338942-1');
      }
    </script>


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?98fcf61fd269408d07dcbc1e49311f9a";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="權咚领域" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">權咚领域</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Making app a work of art.</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://bqlin.github.io/posts/swift_interacts_with_c_language/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/icon.png">
      <meta itemprop="name" content="權咚">
      <meta itemprop="description" content="🤘🤯👾">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="權咚领域">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Swift 与C语言交互
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-08-19 19:16:47" itemprop="dateCreated datePublished" datetime="2021-08-19T19:16:47+08:00">2021-08-19</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/iOS/" itemprop="url" rel="index"><span itemprop="name">iOS</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span><br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>4.7k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>4 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>与C语言交互发生在使用一些C语言编写的API上。C语言的语法会桥接到Swift中对应的语法中。Swift能很好地与C语言交互。</p>
<h2 id="类型">类型</h2>
<p>C语言的基础类型、枚举、结构体、联合体在Swift中都有对应。</p>
<p>其中基础类型是一一对等的。其命名方式对C中的类型采取驼峰式命名之后，加上前缀字母C。</p>
<p>例如：</p>
<ul>
<li><code>int</code> 变成 <code>CInt</code>；</li>
<li><code>unsigned char</code> 变成 <code>CUnsignedChar</code>；</li>
<li><code>unsigned long long</code> 变成 <code>CUnsignedLongLong</code>；</li>
</ul>
<p>其中，只有有三个表示宽字符的类型是特殊的：</p>
<ul>
<li><code>wchat_t</code> 变成 <code>CWideChar</code>；</li>
<li><code>char16_t</code> 变成 <code>CChar16</code>；</li>
<li><code>char32_t</code> 变成 <code>CChar32</code>；</li>
</ul>
<p>这些在Swift对应的基础类型都是typealias，在Swift应应使用typealias类型而不直接使用原生类型。</p>
<h3 id="变量">变量</h3>
<p>全局变量/常量也同样映射到Swift的全局变量/常量中。</p>
<h3 id="枚举结构体联合体">枚举、结构体、联合体</h3>
<p>C中的枚举只是一个普通的基础常量，除非使用<code>NS_×_ENUM</code>、<code>NS_OPTIONS</code>关键字修饰来定义枚举才会映射到Swift中的结构体，但基本使用跟Swift的枚举无异。</p>
<p>结构体则可以直接映射到Swift的结构体。</p>
<p>联合体则是映射到一个结构体中。</p>
<h2 id="函数">函数</h2>
<p>C语言的函数基本能映射到Swift的函数中，除了不支持不固定参数函数，作为替代方案，Swift支持映射<code>va_list</code>表示的可变参数列表。</p>
<p>使用<code>CF_SWIFT_NAME</code>还能把C函数重命名甚至并入extension中。</p>
<h2 id="指针">指针</h2>
<p>Swift的指针都带有Unsafe关键字，表示其使用在编译期可能是不可预测的。</p>
<p>Apple Developer 文档里有 C 指针和 Swift 指针的对应表：</p>
<table>
<thead>
<tr class="header">
<th>C Syntax</th>
<th>Swift Syntax</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>const Type *</code></td>
<td>UnsafePointer</td>
</tr>
<tr class="even">
<td><code>Type *</code></td>
<td>UnsafeMutablePointer</td>
</tr>
<tr class="odd">
<td><code>Type * const *</code></td>
<td>UnsafePointer</td>
</tr>
<tr class="even">
<td><code>Type * __strong *</code></td>
<td>UnsafeMutablePointer</td>
</tr>
<tr class="odd">
<td><code>Type **</code></td>
<td>AutoreleasingUnsafeMutablePointer</td>
</tr>
<tr class="even">
<td><code>const void *</code></td>
<td>UnsafeRawPointer</td>
</tr>
<tr class="odd">
<td><code>void *</code></td>
<td>UnsafeMutableRawPointer</td>
</tr>
</tbody>
</table>
<p>除此以外，Swift还有几种指针表达方式：</p>
<ul>
<li>UnsafeBufferPointer、UnsafeMutableBufferPointer、UnsafeRawBufferPointer、UnsafeMutableRawBufferPointer</li>
<li>OpaquePointer</li>
</ul>
<h3 id="buffer">Buffer</h3>
<p>它相当于在原始内存空间上添加一个view，以步幅（<code>MemoryLayout&lt;T&gt;.stride</code>）单位，以集合的方式访问底层内存。对应C语言的就是数组的访问。</p>
<h3 id="opaquepointer">OpaquePointer</h3>
<p>对于在C回调函数中要传递Swift的对象时，这些对象可能无法桥接到C的类型，这时就要用到OpaquePointer。</p>
<p>转换Swift对象为指针需要用到Unmanaged。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> fooObj <span class="operator">=</span> <span class="type">Foo</span>()</span><br><span class="line"><span class="comment">// 创建Unmanaged&lt;Foo&gt;实例</span></span><br><span class="line"><span class="keyword">let</span> unmanagedFoo <span class="operator">=</span> <span class="type">Unmanaged</span>.passRetained(fooObj)</span><br><span class="line"><span class="comment">// 转换成OpaquePointer，该指针可直接传递到void *的C指针中</span></span><br><span class="line"><span class="keyword">let</span> unmanagedPtr <span class="operator">=</span> unmanagedFoo.toOpaque()</span><br><span class="line"></span><br><span class="line"><span class="comment">// 传递到C函数</span></span><br><span class="line">aFuncWithCallback(unmanagedPtr) &#123;</span><br><span class="line">    (ptr: <span class="type">UnsafeMutableRawPointer</span>?) -&gt; <span class="type">Void</span> <span class="keyword">in</span></span><br><span class="line">    <span class="comment">// 创建Unmanaged&lt;Foo&gt;，并转换为Foo类型</span></span><br><span class="line">    <span class="keyword">let</span> fooObj <span class="operator">=</span></span><br><span class="line">        <span class="type">Unmanaged</span>&lt;<span class="type">Foo</span>&gt;.fromOpaque(ptr<span class="operator">!</span>).takeUnretainedValue()</span><br><span class="line">    <span class="built_in">print</span>(fooObj.foo)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Unmanaged创建和转换都有Retained和Unretained版本，对应的是指是否引用计数操作。Pass方法是否+1引用计数；take方法是否-1引用计数。</p>
<h3 id="字符串指针">字符串指针</h3>
<p>C中表示字符串的 <code>char *</code>，桥接到Swift会变成 <code>UnsafeMutablePointer&lt;Int8&gt;</code>，可以通过相应的构造方法创建String类型。</p>
<h2 id="指针转换">指针转换</h2>
<h3 id="方法参数是指针">方法参数是指针</h3>
<p>调用将指针作为参数的函数时，可以使用隐式转换来传递兼容的指针类型或使用隐式桥接来传递指向变量或数组内容的指针。</p>
<p>若是常量指针参数（<code>UnsafePointer&lt;Type&gt;</code>），可以直接传递：字符串、指定类型数组、指定类型的inout表达式。</p>
<p>若是可变指针参数（<code>UnsafeMutablePointer&lt;Type&gt;</code>），可以直接传递：指定类型数组的inout表达式、指定类型的inout表达式。</p>
<h4 id="向下隐式转换">向下隐式转换</h4>
<p>指针在作为函数参数传递时，可以隐式转换：</p>
<ul>
<li>不可变指针 -&gt; 可变指针</li>
<li>类型指针 -&gt; 原始指针</li>
</ul>
<p>Raw可以直接兼容没有Raw的类型指针。如：需要<code>UnsafeRawPointer</code>类型参数时，可以直接传递<code>UnsafePointer&lt;Type&gt;</code>。</p>
<h4 id="隐式桥接">隐式桥接</h4>
<p>类型变量/常量、数组、字符串，在传递给指针参数时会进行隐式桥接。</p>
<h3 id="swift基本类型---指针">Swift基本类型 -&gt; 指针</h3>
<p>即用指针访问Swift变量/常量。</p>
<p>使用<code>withUnsafexxxPointer</code>函数，在闭包中用指针临时访问指向的变量/常量。</p>
<p><strong>注意：</strong>在闭包中得到的指针不要返回出去。因为这是随外部变量/常量的生命周期影响，会因为其变量/常量销毁而变成野指针。</p>
<p>顶级函数：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 指向具体类型变量的类型指针</span></span><br><span class="line"><span class="keyword">func</span> <span class="title function_">withUnsafePointer</span>&lt;<span class="type">T</span>, <span class="type">Result</span>&gt;(<span class="params">to</span> <span class="params">value</span>: <span class="keyword">inout</span> <span class="type">T</span>, <span class="keyword">_</span> <span class="params">body</span>: (<span class="type">UnsafePointer</span>&lt;<span class="type">T</span>&gt;) <span class="keyword">throws</span> -&gt; <span class="type">Result</span>) <span class="keyword">rethrows</span> -&gt; <span class="type">Result</span></span><br><span class="line"><span class="keyword">func</span> <span class="title function_">withUnsafeMutablePointer</span>&lt;<span class="type">T</span>, <span class="type">Result</span>&gt;(<span class="params">to</span> <span class="params">value</span>: <span class="keyword">inout</span> <span class="type">T</span>, <span class="keyword">_</span> <span class="params">body</span>: (<span class="type">UnsafeMutablePointer</span>&lt;<span class="type">T</span>&gt;) <span class="keyword">throws</span> -&gt; <span class="type">Result</span>) <span class="keyword">rethrows</span> -&gt; <span class="type">Result</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 以字节为单位访问，注意闭包中的参数是Buffer类型</span></span><br><span class="line"><span class="keyword">func</span> <span class="title function_">withUnsafeBytes</span>&lt;<span class="type">T</span>, <span class="type">Result</span>&gt;(<span class="params">of</span> <span class="params">value</span>: <span class="keyword">inout</span> <span class="type">T</span>, <span class="keyword">_</span> <span class="params">body</span>: (<span class="type">UnsafeRawBufferPointer</span>) <span class="keyword">throws</span> -&gt; <span class="type">Result</span>) <span class="keyword">rethrows</span> -&gt; <span class="type">Result</span></span><br><span class="line"><span class="keyword">func</span> <span class="title function_">withUnsafeMutableBytes</span>&lt;<span class="type">T</span>, <span class="type">Result</span>&gt;(<span class="params">of</span> <span class="params">value</span>: <span class="keyword">inout</span> <span class="type">T</span>, <span class="keyword">_</span> <span class="params">body</span>: (<span class="type">UnsafeMutableRawBufferPointer</span>) <span class="keyword">throws</span> -&gt; <span class="type">Result</span>) <span class="keyword">rethrows</span> -&gt; <span class="type">Result</span></span><br></pre></td></tr></table></figure>
<h4 id="数组中的应用">数组中的应用</h4>
<ul>
<li><code>withUnsafeBytes</code>、<code>withUnsafeMutableBytes</code></li>
<li><code>withUnsafeBufferPointer</code>、<code>withUnsafeMutableBufferPointer</code></li>
</ul>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// withUnsafeMutableBytes应用</span></span><br><span class="line"><span class="keyword">var</span> numbers: [<span class="type">Int32</span>] <span class="operator">=</span> [<span class="number">0</span>, <span class="number">0</span>]</span><br><span class="line"><span class="keyword">var</span> byteValues: [<span class="type">UInt8</span>] <span class="operator">=</span> [<span class="number">0x01</span>, <span class="number">0x00</span>, <span class="number">0x00</span>, <span class="number">0x00</span>, <span class="number">0x02</span>, <span class="number">0x00</span>, <span class="number">0x00</span>, <span class="number">0x00</span>]</span><br><span class="line"></span><br><span class="line">numbers.withUnsafeMutableBytes &#123; destBytes <span class="keyword">in</span></span><br><span class="line">    byteValues.withUnsafeBytes &#123; srcBytes <span class="keyword">in</span></span><br><span class="line">        destBytes.copyBytes(from: srcBytes)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// numbers == [1, 2]</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// withUnsafeBytes应用</span></span><br><span class="line"><span class="keyword">var</span> numbers <span class="operator">=</span> [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]</span><br><span class="line"><span class="keyword">var</span> byteBuffer: [<span class="type">UInt8</span>] <span class="operator">=</span> []</span><br><span class="line">numbers.withUnsafeBytes &#123;</span><br><span class="line">    byteBuffer.append(contentsOf: <span class="variable">$0</span>)</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// byteBuffer == [1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, ...]</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// withUnsafeBufferPointer应用</span></span><br><span class="line"><span class="keyword">let</span> numbers <span class="operator">=</span> [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>]</span><br><span class="line"><span class="keyword">let</span> sum <span class="operator">=</span> numbers.withUnsafeBufferPointer &#123; buffer -&gt; <span class="type">Int</span> <span class="keyword">in</span></span><br><span class="line">    <span class="keyword">var</span> result <span class="operator">=</span> <span class="number">0</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">stride</span>(from: buffer.startIndex, to: buffer.endIndex, by: <span class="number">2</span>) &#123;</span><br><span class="line">        result <span class="operator">+=</span> buffer[i]</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// &#x27;sum&#x27; == 9</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// withUnsafeMutableBufferPointer应用</span></span><br><span class="line"><span class="keyword">var</span> numbers <span class="operator">=</span> [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>]</span><br><span class="line">numbers.withUnsafeMutableBufferPointer &#123; buffer <span class="keyword">in</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">stride</span>(from: buffer.startIndex, to: buffer.endIndex <span class="operator">-</span> <span class="number">1</span>, by: <span class="number">2</span>) &#123;</span><br><span class="line">        buffer.swapAt(i, i <span class="operator">+</span> <span class="number">1</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">print</span>(numbers)</span><br><span class="line"><span class="comment">// Prints &quot;[2, 1, 4, 3, 5]&quot;</span></span><br></pre></td></tr></table></figure>
<h4 id="字符串中的应用">字符串中的应用</h4>
<ul>
<li><code>withCString</code></li>
<li><code>withUTF8</code></li>
</ul>
<h4 id="data中的应用">Data中的应用</h4>
<ul>
<li><code>withUnsafeBytes</code></li>
<li><code>withUnsafeMutableBytes</code></li>
</ul>
<h3 id="指针类型转换">指针类型转换</h3>
<p>注意Swift中的指针类型不存在继承关系。</p>
<h4 id="类型指针---原始指针">类型指针 -&gt; 原始指针</h4>
<p>直接用原始指针的构造方法进行转换，如果是作为入参，则无需转换直接传递即可。</p>
<h4 id="原始指针---类型指针">原始指针 -&gt; 类型指针</h4>
<p>永久绑定：<code>bindMemory</code>、<code>assumingMemoryBound</code>，两者操作的类型必须一致。</p>
<p>这种方式需要从原始指针调用，如果是类型指针要转换类型，则须转换为原始指针，再调用绑定类型方法。<code>bindMemory</code>会导致原来的类型指针是未定义的，如果修改后兼容原来。</p>
<p>临时转换访问：<code>withMemoryRebound</code>，该方法的访问发生在闭包参数中。</p>
<h3 id="访问指向的值">访问指向的值</h3>
<p>若是类型指针（<code>UnsafePointer&lt;Type&gt;</code>），可直接访问<code>pointee</code>，可读写。</p>
<p>若是原始指针（<code>UnsafeRawPointer</code>），使用<code>load</code>方法，返回指定偏移的具体类型。只读。</p>
<p>当然对于可变原始指针（<code>UnsafeMutableRawPointer</code>），有对应的写入方法：</p>
<ul>
<li><code>copyMemory</code>：从其他原始指针拷贝字节数据</li>
<li><code>storeBytes</code>：写入具体类型</li>
</ul>
<h2 id="c指针使用注意">C指针使用注意</h2>
<p>在 Core Foundation 里，几乎所有用 Create 和 Copy 开头的函数，只要它们返回一个非托管的对象，我们几乎总是应该使用 takeRetainedValue() 方法来读取。</p>
<p><a target="_blank" rel="noopener" href="https://nshipster.cn/unmanaged/">Unmanaged - NSHipster</a></p>
<h2 id="参考">参考</h2>
<ul>
<li><a target="_blank" rel="noopener" href="https://developer.apple.com/documentation/swift/swift_standard_library/manual_memory_management">Manual Memory Management | Apple Developer Documentation</a></li>
<li><a target="_blank" rel="noopener" href="https://developer.apple.com/documentation/swift/swift_standard_library/c_interoperability">C Interoperability | Apple Developer Documentation</a></li>
</ul>

    </div>

    
    
    
        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Apple/" rel="tag"># Apple</a>
              <a href="/tags/Swift/" rel="tag"># Swift</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/posts/kvo/" rel="prev" title="KVO">
      <i class="fa fa-chevron-left"></i> KVO
    </a></div>
      <div class="post-nav-item">
    <a href="/posts/ffmpeg_api/" rel="next" title="FFmpeg基本API：常用操作">
      FFmpeg基本API：常用操作 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="gitalk-container"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%B1%BB%E5%9E%8B"><span class="nav-text">类型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%98%E9%87%8F"><span class="nav-text">变量</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%9E%9A%E4%B8%BE%E7%BB%93%E6%9E%84%E4%BD%93%E8%81%94%E5%90%88%E4%BD%93"><span class="nav-text">枚举、结构体、联合体</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%87%BD%E6%95%B0"><span class="nav-text">函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%8C%87%E9%92%88"><span class="nav-text">指针</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#buffer"><span class="nav-text">Buffer</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#opaquepointer"><span class="nav-text">OpaquePointer</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%8C%87%E9%92%88"><span class="nav-text">字符串指针</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%8C%87%E9%92%88%E8%BD%AC%E6%8D%A2"><span class="nav-text">指针转换</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%96%B9%E6%B3%95%E5%8F%82%E6%95%B0%E6%98%AF%E6%8C%87%E9%92%88"><span class="nav-text">方法参数是指针</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%90%91%E4%B8%8B%E9%9A%90%E5%BC%8F%E8%BD%AC%E6%8D%A2"><span class="nav-text">向下隐式转换</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E9%9A%90%E5%BC%8F%E6%A1%A5%E6%8E%A5"><span class="nav-text">隐式桥接</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#swift%E5%9F%BA%E6%9C%AC%E7%B1%BB%E5%9E%8B---%E6%8C%87%E9%92%88"><span class="nav-text">Swift基本类型 -&gt; 指针</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%95%B0%E7%BB%84%E4%B8%AD%E7%9A%84%E5%BA%94%E7%94%A8"><span class="nav-text">数组中的应用</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B8%AD%E7%9A%84%E5%BA%94%E7%94%A8"><span class="nav-text">字符串中的应用</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#data%E4%B8%AD%E7%9A%84%E5%BA%94%E7%94%A8"><span class="nav-text">Data中的应用</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%8C%87%E9%92%88%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2"><span class="nav-text">指针类型转换</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E7%B1%BB%E5%9E%8B%E6%8C%87%E9%92%88---%E5%8E%9F%E5%A7%8B%E6%8C%87%E9%92%88"><span class="nav-text">类型指针 -&gt; 原始指针</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%8E%9F%E5%A7%8B%E6%8C%87%E9%92%88---%E7%B1%BB%E5%9E%8B%E6%8C%87%E9%92%88"><span class="nav-text">原始指针 -&gt; 类型指针</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%AE%BF%E9%97%AE%E6%8C%87%E5%90%91%E7%9A%84%E5%80%BC"><span class="nav-text">访问指向的值</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#c%E6%8C%87%E9%92%88%E4%BD%BF%E7%94%A8%E6%B3%A8%E6%84%8F"><span class="nav-text">C指针使用注意</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8F%82%E8%80%83"><span class="nav-text">参考</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="權咚"
      src="/images/icon.png">
  <p class="site-author-name" itemprop="name">權咚</p>
  <div class="site-description" itemprop="description">🤘🤯👾</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">84</span>
          <span class="site-state-item-name">文章</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">10</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/bqlin" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;bqlin" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://weibo.com/hearingdog" title="Weibo → https:&#x2F;&#x2F;weibo.com&#x2F;hearingdog" rel="noopener" target="_blank"><i class="fab fa-weibo fa-fw"></i>Weibo</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      Links
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://xiaozhuanlan.com/metal-reference-translation" title="https:&#x2F;&#x2F;xiaozhuanlan.com&#x2F;metal-reference-translation" rel="noopener" target="_blank">Metal内参</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://xiaozhuanlan.com/wwdc21" title="https:&#x2F;&#x2F;xiaozhuanlan.com&#x2F;wwdc21" rel="noopener" target="_blank">WWDC21 内参</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2016 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">權咚</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="站点总字数">279k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">4:14</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/pangu@4/dist/browser/pangu.min.js"></script>

<script src="/js/utils.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/js/local-search.js"></script>











<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme    : 'default',
      logLevel : 3,
      flowchart: { curve     : 'linear' },
      gantt    : { axisFormat: '%m/%d/%Y' },
      sequence : { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>


  

  

  

<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.css">

<script>
NexT.utils.loadComments(document.querySelector('#gitalk-container'), () => {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js', () => {
    var gitalk = new Gitalk({
      clientID    : '7ed324dbfd2741c35c0e',
      clientSecret: '75a59e1f6a55202c4a1b0ec3570ad5b5dccbc390',
      repo        : 'bqlin.github.io',
      owner       : 'bqlin',
      admin       : ['bqlin'],
      id          : 'e63a84eaae3af5495b3c33681a543f12',
        language: 'zh-CN',
      distractionFreeMode: true
    });
    gitalk.render('gitalk-container');
  }, window.Gitalk);
});
</script>

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"scale":1,"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"right","vOffset":-100},"mobile":{"show":false,"scale":0.5},"log":false});</script></body>
</html>
